<?php
$count = 0;
$current = ($_GET['current'] ? $_GET['current']  : 0);
?>
<script type="text/javascript">
function dateToUnixTime(date){
	var year = date.substr(0,4);
	var month = date.substr(5,2);
	var day = date.substr(8,2);
	var hour = date.substr(11,2);
	var minute = date.substr(14,2);
	var second = date.substr(17,2);
	var date = new Date(year, month, day, hour, minute, second);
	return date.getTime();
}

function Observer() {
    this.fns = [];
}
Observer.prototype = {
    subscribe : function(fn) {
        this.fns.push(fn);
    },
    unsubscribe : function(fn) {
        this.fns = this.fns.filter(
            function(el) {
                if ( el !== fn ) {
                    return el;
                }
            }
        );
    },
    fire : function(o, thisObj) {
        var scope = thisObj || window;
        this.fns.forEach(
            function(el) {
                el.call(scope, o);
            }
        );
    }
};

var order_list = new Observer;
var order_detail = new Observer;
var glass_detail = new Observer;

order_list.remove = function (id){
	for(var i in order_list.orders){
		if(order_list.orders[i]['@attributes'].id==id){
			order_list.orders.splice(i,1);
			this.fire('order deleted');
		}
	}
};

function get_recipe(recipe_id){
	var http = new XMLHttpRequest();
	var url = "<?php print $this->url(array('controller'=>'recipe','module'=>'website','action'=>'get'),'rest'); ?>/"+recipe_id+"?format=json";
	http.open("GET", url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			var result = eval("(" + http.responseText + ")");
			for(var i in order_list.orders){
				if(order_list.orders[i]['@attributes'].recipeId == recipe_id){
					order_list.orders[i].recipe = result.rsp.recipe;
				}
			}
		}
	};
	http.send();
}

function get_glass(glass_id,order){
	var http = new XMLHttpRequest();
	var url = "<?php print $this->url(array('controller'=>'glass','module'=>'website','action'=>'get'),'rest'); ?>/"+glass_id+"?format=json";
	http.open("GET", url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			var result = eval("(" + http.responseText + ")");
			order.glass = result.rsp.glass;
			glass_detail.fire('glass data retrieved');
		}
	};
	http.send();
}

function get_member(member_id,objects){
	var http = new XMLHttpRequest();
	var url = "<?php print $this->url(array('controller'=>'member','module'=>'website','action'=>'get'),'rest'); ?>/"+member_id+"?format=json";
	http.open("GET", url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			// parse response
			var result = eval("(" + http.responseText + ")");
			// update all given objects
			// @todo: replace with observer pattern
			for(var obj in objects){
				objects[obj].innerHTML = member_id;
				objects[obj].innerHTML = result.rsp.member['@attributes'].firstname + ' ' + result.rsp.member['@attributes'].lastname;
			}
			// add to order objects
			for(var i in order_list.orders){
				if(order_list.orders[i]['@attributes'].member == member_id){
					order_list.orders[i].member = result.rsp.member;
				}
			}
		}
	};
	http.send();
}

// build orders
order_list.subscribe(function(){
	// empty order list
	document.getElementById('order_list').innerHTML = '';
	// create order list
	for(var orderNr in order_list.orders){
		if(orderNr < 5*(current_page) && orderNr >= 5*(current_page-1)){
			order = order_list.orders[orderNr];
			document.getElementById('order_list').innerHTML = 
				document.getElementById('order_list').innerHTML + 
				'<li id="order_'+order['@attributes'].id+'" onclick="switch_order('+order['@attributes'].id+');">'+
				'<img src="/website/recipe/'+order['@attributes'].recipeId+'?format=image" alt="" />'+
				'<div>'+
				'<span class="title">'+order['@attributes'].recipeName+'</span>'+
				'</a><br /><span class="subline">vor '+ parseInt(((new Date).getTime()/1000 - dateToUnixTime(order['@attributes'].orderDate)/1000)/60) +
				' min, von <span class="member_'+order['@attributes'].member+'"></span></span><br />'+
				'<input type="button" value="stornieren" id="cancel_'+order['@attributes'].id+'" class="grey hide" /> '+
				'<input type="button" value="fertig" onclick="completed('+order['@attributes'].id+');" '+
				'class="pink right hide" id="complete_'+order['@attributes'].id+'" /></div><hr /></li>';
				get_member(order['@attributes'].member,document.getElementsByClassName('member_'+order['@attributes'].member));
		}
	}
	// make first item active one
	if(document.getElementById('order_list').children[0]){
		document.getElementById('order_list').children[0].className='active page_'+current_page;
		var nextOrderId = document.getElementById('order_list').children[0].id.substr(6);
		document.getElementById('cancel_'+nextOrderId).className='grey';
		document.getElementById('complete_'+nextOrderId).className='pink right';
	}
	// update open_orders and completed_orders
	document.getElementById('open_orders').innerHTML = order_list.orders.length;
	document.getElementById('completed_orders').innerHTML = parseInt(document.getElementById('completed_orders').innerHTML) + 1;  
	document.getElementById('to_page').innerHTML = parseInt((order_list.orders.length - 1) / 5) + 1;
});

//disable back button
order_list.subscribe(function (){
	if(order_list.orders.length >= current_page*5){
		document.getElementById('back_button').disabled = 'disabled';
		document.getElementById('back_button').className = 'grey left margin_top';
	} else {
		document.getElementById('back_button').disabled = '';
		document.getElementById('back_button').className = 'pink left margin_top';
	}
});

//disable forward button
order_list.subscribe(function (){
	if(order_list.orders.length <= current_page*5){
		document.getElementById('forward_button').disabled = 'disabled';
		document.getElementById('forward_button').className = 'grey right margin_top';
	} else {
		document.getElementById('forward_button').disabled = '';
		document.getElementById('forward_button').className = 'pink right margin_top';
	}
});

var current_page = 1;

function show_order_page(page){
	current_page = page;
	order_list.fire('page changed');
}

function completed(orderId){ 
	var http = new XMLHttpRequest();
	var url = "<?php print $this->url(array('controller'=>'order','module'=>'website','action'=>'put')); ?>?format=json";
	var params = "id="+orderId+"&status=completed&member=<?php print 54; ?>&hashCode=57c14f9f45d465f03533cea5d69bd5f5";
	http.open("PUT", url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			var result = eval("(" + http.responseText + ")");
			if(result.rsp.order['@attributes'].status=='completed'){
				order_list.remove(orderId);
			}
		}
	};
	http.send(params);
}

var current_order;

function switch_order(orderId){
	for(var i in order_list.orders){
		if(order_list.orders[i]['@attributes'].id==orderId){
			current_order = order_list.orders[i];
		}
	}
	order_detail.fire('order changed');
}

// change detail view
order_detail.subscribe(function(){
	get_glass(current_order.recipe['@attributes'].glass,current_order);
	document.getElementById('detail_recipe_name').innerHTML = current_order.recipe['@attributes'].name;
	document.getElementById('detail_recipe_image').src = '/website/recipe/'+current_order.recipe['@attributes'].id+'?format=image';
	document.getElementById('detail_recipe_glass_image').src = '/website/glass/'+current_order.recipe['@attributes'].glass+'?format=image';
	document.getElementById('detail_recipe_volume').innerHTML = current_order.recipe['@attributes'].volumeCl;
	document.getElementById('detail_recipe_alcohol').innerHTML = current_order.recipe['@attributes'].alcoholLevel;
	document.getElementById('detail_recipe_order_time').innerHTML = parseInt(((new Date).getTime()/1000 - dateToUnixTime(current_order['@attributes'].orderDate)/1000)/60);
	document.getElementById('detail_recipe_member').innerHTML = current_order.member['@attributes'].firstname + ' ' + current_order.member['@attributes'].lastname;
	document.getElementById('detail_recipe_comment_member').innerHTML = current_order.member['@attributes'].firstname + ' ' + current_order.member['@attributes'].lastname;
	if(current_order['@attributes'].comment){
		document.getElementById('detail_recipe_comment').className='info comment';	
		document.getElementById('detail_recipe_comment_text').innerHTML = current_order['@attributes'].comment;
	} else {
		document.getElementById('detail_recipe_comment').className='info comment hide';
	}
	document.getElementById('detail_recipe_ingredients').innerHTML = '';
	for(var i in current_order.recipe.components.component){
		document.getElementById('detail_recipe_ingredients').innerHTML +=
			'<li>'+current_order.recipe.components.component[i]['@attributes'].amount + ' ' +
			current_order.recipe.components.component[i]['@attributes'].unit + ' ' +
			current_order.recipe.components.component[i]['@attributes'].name+'</li>';
			// + '<ul><li>bevorzugt '+' von '+'</li></ul>';
	}
	document.getElementById('detail_recipe_instruction').innerHTML = '';
	var instructions = current_order.recipe['@attributes'].instruction.split('.');
	for(var i in instructions){
		if(instructions[i]!=''){
			document.getElementById('detail_recipe_instruction').innerHTML +=
				'<li>'+instructions[i]+'.</li>';
		}
	}
	if(current_order.recipe.videos.video){
		document.getElementById('detail_recipe_video_icon').className = 'video_image left';
		document.getElementById('detail_recipe_video').src = 'http://www.youtube.com/embed/'+current_order.recipe.videos.video['@attributes'].url.replace(/http:\/\/www.youtube.com\/v\//,"");
		document.getElementById('detail_recipe_video_comment').innerHTML = current_order.recipe.videos.video['@attributes'].description;
	} else {
		document.getElementById('detail_recipe_video_icon').className = 'video_image left hide';
		document.getElementById('detail_recipe_video').src = '';
		document.getElementById('detail_recipe_video_comment').innerHTML = '';
	}
});

// change glass name
glass_detail.subscribe(function(){
	document.getElementById('detail_recipe_glass_name').innerHTML = current_order.glass['@attributes'].name;
});

function init(){
	// get order list
	var http = new XMLHttpRequest();
	var url = "<?php print $this->url(array('controller'=>'order','module'=>'website','action'=>'index')); ?>?format=json&party=2&member=54&hashCode=57c14f9f45d465f03533cea5d69bd5f5";
	http.open("GET", url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			// build order_list array
			var result = eval("(" + http.responseText + ")");
			order_list.orders = result.rsp.orders.order;
			for(var order_nr in order_list.orders){
				get_recipe(order_list.orders[order_nr]['@attributes'].recipeId);
			}
			order_list.fire('data initialized');
		}
	};
	http.send();
}

init();

function order_form(show){
	var order_form = document.getElementById('order_form');
	var order_form2 = document.getElementById('order_form2');
	if(show){
		order_form.style.display='block';
		order_form2.style.display='block';
	} else {
		order_form.style.display='none';
		order_form2.style.display='none';
	}
}
</script>
<div class="order">
<div class="block"><span class="pink">Bestellungen:</span> <input
	type="submit" value="Neue Bestellung" name="action" class="pink right"
	onclick="order_form(true);" />
<hr class="light" />
<ul id="order_list"></ul>
<p class="block_info">offene Bestellungen: <span id="open_orders"></span><br />
abgearbeitete Bestellungen: <span id="completed_orders"><?php print $this->completedOrdersCount; ?></span><br />
<span class="margin_top" style="display: inline-block">Seite <span
	id="from_page">1</span>/<span id="to_page"></span></span> <input
	type="button" class="grey left margin_top" value="&lt; zurück"
	id="back_button" onclick="show_order_page(current_page-1);" /> <input
	type="button" class="grey right margin_top" id="forward_button"
	value="weiter &gt;" onclick="show_order_page(current_page+1);" /></p>
</div>
<div class="bestellungen">
<div class="right center smaller"><img id="detail_recipe_image" src=""
	alt="" class="recipe_image" /><br />
<br />
<img id="detail_recipe_glass_image" src="" alt="" class="glass" /><br />
<span id="detail_recipe_glass_name"></span><br />
<br />
<img src="/img/volumen.png" alt="" class="volume" /><br />
<span id="detail_recipe_volume"></span> cl<br />
<br />
<img src="/img/prozent.png" alt="" class="volume" /><br />
<span id="detail_recipe_alcohol"></span> % Alkohol</div>
<div class="left">
<h2 class="pink left" id="detail_recipe_name"></h2>
<img src="/img/video.png" alt="" class="video_image left" id="detail_recipe_video_icon"
	onclick="document.getElementById('video').style.display='block';document.getElementById('order_form').style.display='block';" /> <span
	class="subline clear">bestellt vor <span id="detail_recipe_order_time"></span>
min</span> <br />
<p class="info comment hide" id="detail_recipe_comment">Kommentar von <span
	id="detail_recipe_comment_member"></span>: <span
	id="detail_recipe_comment_text"></span></p>
<span class="pink">Besteller:</span><br />
<span id="detail_recipe_member"></span><br />
<br />
<span class="pink">Zutaten:</span>
<ul id="detail_recipe_ingredients">
</ul>
<!-- <span class="pink">Deko:</span>
<ul>
</ul> --> <span class="pink">Zubereitung:</span>
<ul style="width: 340px;" id="detail_recipe_instruction">
</ul>
</div>
<!-- <p class="clear center info">Achtung: Mehrere Bestellungen wurden
zusammengefasst!</p> --></div>
<div id="order_form" class="hide"></div>
<div id="order_form2" class="hide">
<h2 class="pink">Neue Bestellung</h2>
<br />
<label class="margin_bottom">Gast: <select class="right">
<?php if(is_array($this->guests)) { foreach ($this->guests as $guest) { ?>
	<option><?php print $guest->firstname.' '.$guest->lastname; ?></option>
	<?php } } ?>
</select></label> <label class="margin_bottom">Rezept: <select
	class="right">
	<?php if(is_array($this->recipes)) { foreach ($this->recipes as $recipe) { ?>
	<option><?php print $recipe->name; ?></option>
	<?php } } ?>
</select></label> Kommentar: <textarea rows="4" cols="43"></textarea><br />
<input type="submit" value="Bestellen" name="action"
	class="pink right margin_top" /><a href=""
	class="button grey right margin_right margin_top"
	onclick="order_form(false);">Abbrechen</a></div>
<div id="video" class="hide">
<h2 class="pink">Videoanleitung</h2>
	<?php ?>
<p><strong><?php $videos = $this->orders[$count]->getRecipe()->getVideos(); print $videos[0]->name; ?></strong></p>
<iframe width="425" height="350" src=""
	id="detail_recipe_video" frameborder="0"></iframe>
<p style="text-align: left; padding-top: 0.5em;"><em><strong>Videohinweis:</strong>
<span id="detail_recipe_video_comment"></span></em></p>
<a href="#" class="button pink right margin_right margin_top"
	onclick="document.getElementById('video').style.display='none';document.getElementById('order_form').style.display='none';">Schließen</a></div>
</div>
